document.addEventListener('DOMContentLoaded', () => {
  // 主要数据
  const state = {
    selectedAmount: 100,
    maxAmount: 240,
    minAmount: 10,
    touchStartY: 0,
    touchStartAmount: 100,
    theme: 'dark',
    animOn: false, // 禁用动画效果
    amountBounce: false,
    waveTimer: null,
    isSliding: false,
    slideEndTimer: null,
    waveIntensity: 0.05, // 默认显示一点波纹效果，看起来更自然
    waveDecayTimer: null,
    themeColors: {
      pink: {
        name: '粉色',
        main: '#ff69b4',
        bottleTop: '#fff0f5',
        bottleBottom: '#ffb6c1',
        bottleStroke: '#ffb6c1',
        milkTop: '#fff0f5',
        milkBottom: '#ffb6c1',
        scale: '#ffb6c1',
        shadow: '#ffb6c1'
      },
      blue: {
        name: '蓝色',
        main: '#4285f4',
        bottleTop: '#e3f2fd',
        bottleBottom: '#90caf9',
        bottleStroke: '#90caf9',
        milkTop: '#e3f2fd',
        milkBottom: '#90caf9',
        scale: '#90caf9',
        shadow: '#90caf9'
      },
      green: {
        name: '绿色',
        main: '#34a853',
        bottleTop: '#e8f5e8',
        bottleBottom: '#81c784',
        bottleStroke: '#81c784',
        milkTop: '#e8f5e8',
        milkBottom: '#81c784',
        scale: '#81c784',
        shadow: '#81c784'
      },
      purple: {
        name: '紫色',
        main: '#9c27b0',
        bottleTop: '#f3e5f5',
        bottleBottom: '#ce93d8',
        bottleStroke: '#ce93d8',
        milkTop: '#f3e5f5',
        milkBottom: '#ce93d8',
        scale: '#ce93d8',
        shadow: '#ce93d8'
      },
      orange: {
        name: '橙色',
        main: '#ff9800',
        bottleTop: '#fff8e1',
        bottleBottom: '#ffcc02',
        bottleStroke: '#ffcc02',
        milkTop: '#fff8e1',
        milkBottom: '#ffcc02',
        scale: '#ffcc02',
        shadow: '#ffcc02'
      },
      dark: {
        name: '深色',
        main: '#333',
        bottleTop: '#444',
        bottleBottom: '#222',
        bottleStroke: '#fff',
        milkTop: '#fff',
        milkBottom: '#bbb',
        scale: '#fff',
        shadow: '#000'
      }
    },
    scaleMarks: [50, 100, 150, 200, 240]
  };

  // DOM元素
  const bottleWrapper = document.getElementById('bottleWrapper');
  const milkAmountDisplay = document.getElementById('milkAmountDisplay');
  const milkAmountMain = milkAmountDisplay.querySelector('.milk-amount-main');
  const milkWavePath = document.getElementById('milkWavePath');
  const milkWaveHighlightPath = document.getElementById('milkWaveHighlightPath');
  const bottleContainer = document.querySelector('.bottle-container');
  const themeButtons = document.querySelectorAll('.theme-switch button');
  const scaleMarksGroup = document.getElementById('scaleMarks');
  
  // 初始化刻度线
  initScaleMarks();
  
  // 初始化波浪动画
  startWaveAnimation();
  
  // 事件监听
  bottleWrapper.addEventListener('touchstart', onTouchStart, { passive: false });
  bottleWrapper.addEventListener('touchmove', onTouchMove, { passive: false });
  bottleWrapper.addEventListener('touchend', onTouchEnd, { passive: false });
  
  // 鼠标事件（也支持拖拽）
  bottleWrapper.addEventListener('mousedown', onMouseDown);
  
  // 主题切换
  themeButtons.forEach(button => {
    button.addEventListener('click', () => {
      const themeName = button.getAttribute('data-theme');
      switchTheme(themeName);
      
      // 移除其他按钮的active类
      themeButtons.forEach(btn => btn.classList.remove('active'));
      // 添加当前按钮的active类
      button.classList.add('active');
    });
  });

  // 更新奶瓶显示
  updateBottleDisplay();
  
  // 函数定义
  function getMilkHeight() {
    const percent = (state.selectedAmount - state.minAmount) / (state.maxAmount - state.minAmount);
    return Math.max(percent * 220, 8);
  }
  
  function getScaleY(mark) {
    // 刻度线Y坐标
    const percent = (mark - state.minAmount) / (state.maxAmount - state.minAmount);
    const bottleBodyStart = 150;
    const bottleBodyEnd = 270;
    const bottleBodyHeight = bottleBodyEnd - bottleBodyStart;
    return bottleBodyEnd - Math.max(percent * bottleBodyHeight, 8);
  }
  
  function initScaleMarks() {
    // 清空现有刻度
    scaleMarksGroup.innerHTML = '';
    
    // 只添加刻度线，不添加文字
    state.scaleMarks.forEach(mark => {
      const y = getScaleY(mark);
      
      // 创建刻度线
      const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
      line.setAttribute('x1', '115');
      line.setAttribute('y1', y);
      line.setAttribute('x2', '130');  // 增加刻度线长度
      line.setAttribute('y2', y);
      line.setAttribute('stroke', state.themeColors[state.theme].scale);
      line.setAttribute('stroke-width', '3');  // 增加刻度线宽度
      line.setAttribute('opacity', '0.9');  // 增加不透明度
      
      // 添加到组
      scaleMarksGroup.appendChild(line);
      
      // 移除刻度文本创建代码
    });
  }
  
  function calculateMilkWavePath() {
    const y = 292 - getMilkHeight();

    // 当波纹强度很低时，混合轻微波动和衰减波纹
    if (state.waveIntensity <= 0.1) {
      // 计算轻微波动
      const gentleAmp = 0.9; // 增加波浪幅度
      const gentleFreq = 1.5; // 较低的频率
      const step = 18; // 减小步长，让波浪更精细
      let d = `M-76,${y}`;
      for (let x = -76; x <= 216; x += step) {
        const time = Date.now() / 8000; // 非常慢的滚动速度
        const gentleWaveY = y + Math.sin((x / 60 + time) * Math.PI * gentleFreq) * gentleAmp;

        // 如果还有衰减波纹，则混合两种效果
        let finalWaveY = gentleWaveY;
        if (state.waveIntensity > 0.01) {
          const decayTime = Date.now() / 2000;
          const decayWaveY = y + Math.sin((x / 20 + decayTime) * Math.PI * 3) * (3 * state.waveIntensity);
          // 平滑混合：衰减波纹逐渐减弱，轻微波动逐渐增强
          const mixRatio = state.waveIntensity / 0.1; // 0.01-0.1 映射到 0.1-1
          finalWaveY = gentleWaveY * (1 - mixRatio) + decayWaveY * mixRatio;
        }

        d += ` Q${x + step / 2},${finalWaveY - gentleAmp / 3} ${x + step},${finalWaveY}`;
      }
      d += ` V292 H-76 Z`;
      return d;
    }

    // 根据波纹强度调整波纹参数
    const baseAmp = 3.5; // 增加基础波纹幅度
    const amp = baseAmp * state.waveIntensity, // 根据强度调整幅度
      freq = 3, // 增加波纹频率
      step = 10; // 减小步长，让波纹更精细
    let d = `M-76,${y}`;
    for (let x = -76; x <= 216; x += step) {
      const time = Date.now() / 2000; // 加快滚动速度
      const waveY = y + Math.sin((x / 20 + time) * Math.PI * freq) * amp;
      d += ` Q${x + step / 2},${waveY - amp / 2} ${x + step},${waveY}`;
    }
    d += ` V292 H-76 Z`;
    return d;
  }
  
  function calculateMilkWaveHighlightPath() {
    const y = 292 - getMilkHeight() - 2;

    // 当波纹强度很低时，混合轻微波动和衰减波纹
    if (state.waveIntensity <= 0.1) {
      // 计算轻微高光波动
      const gentleAmp = 0.6; // 增加高光波浪幅度
      const gentleFreq = 1.2; // 稍微不同的频率
      const step = 18; // 减小步长，让波浪更精细
      let d = `M-76,${y}`;
      for (let x = -76; x <= 216; x += step) {
        const time = Date.now() / 9000; // 稍微不同的速度
        const gentleWaveY = y + Math.sin((x / 70 + time + 0.3) * Math.PI * gentleFreq) * gentleAmp;

        // 如果还有衰减波纹，则混合两种效果
        let finalWaveY = gentleWaveY;
        if (state.waveIntensity > 0.01) {
          const decayTime = Date.now() / 2500;
          const decayWaveY = y + Math.sin((x / 25 + decayTime + 0.5) * Math.PI * 2.5) * (2 * state.waveIntensity);
          // 平滑混合：衰减波纹逐渐减弱，轻微波动逐渐增强
          const mixRatio = state.waveIntensity / 0.1; // 0.01-0.1 映射到 0.1-1
          finalWaveY = gentleWaveY * (1 - mixRatio) + decayWaveY * mixRatio;
        }

        d += ` Q${x + step / 2},${finalWaveY - gentleAmp / 3} ${x + step},${finalWaveY}`;
      }
      d += ` V292 H-76 Z`;
      return d;
    }

    // 根据波纹强度调整高光波纹参数
    const baseAmp = 2.5; // 增加基础高光波纹幅度
    const amp = baseAmp * state.waveIntensity,
      freq = 2.5,
      step = 10; // 减小步长，让波纹更精细
    let d = `M-76,${y}`;
    for (let x = -76; x <= 216; x += step) {
      const time = Date.now() / 2500; // 稍微不同的速度
      const waveY = y + Math.sin((x / 25 + time + 0.5) * Math.PI * freq) * amp;
      d += ` Q${x + step / 2},${waveY - amp / 2} ${x + step},${waveY}`;
    }
    d += ` V292 H-76 Z`;
    return d;
  }
  
  function updateBottleDisplay() {
    // 更新奶量显示
    milkAmountMain.textContent = state.selectedAmount;
    
    // 更新波浪路径
    milkWavePath.setAttribute('d', calculateMilkWavePath());
    milkWaveHighlightPath.setAttribute('d', calculateMilkWaveHighlightPath());
    
    // 更新奶瓶笔画颜色
    const bottleStrokes = document.querySelectorAll('.bottle-svg .a, .bottle-svg .c');
    bottleStrokes.forEach(path => {
      path.setAttribute('stroke', state.themeColors[state.theme].bottleStroke);
    });
    
    // 更新波浪填充颜色
    milkWavePath.setAttribute('fill', `url(#milkGradient-${state.theme})`);
    milkWaveHighlightPath.setAttribute('fill', `url(#highlightGradient-${state.theme})`);
  }
  
  function startWaveAnimation() {
    // 清理之前的定时器
    if (state.waveTimer) {
      clearInterval(state.waveTimer);
    }
    // 启动新的波纹动画定时器，每16ms更新一次（约60fps）
    state.waveTimer = setInterval(() => {
      updateBottleDisplay();
    }, 16);
  }
  
  function switchTheme(themeName) {
    state.theme = themeName;
    
    // 更新容器类名
    bottleContainer.className = `bottle-container ${themeName}`;
    
    // 更新刻度线颜色
    initScaleMarks();
  }
  
  function onTouchStart(e) {
    state.touchStartY = e.touches[0].clientY;
    state.touchStartAmount = state.selectedAmount;

    // 开始滑动，启用波纹动画
    state.isSliding = true;
    state.waveIntensity = 1; // 立即设置为最大波纹强度

    // 清理之前的定时器
    if (state.slideEndTimer) {
      clearTimeout(state.slideEndTimer);
    }
    if (state.waveDecayTimer) {
      clearInterval(state.waveDecayTimer);
    }
    
    // 阻止滚动
    e.preventDefault();
  }
  
  function onTouchMove(e) {
    if (!state.isSliding) return;
    
    const deltaY = state.touchStartY - e.touches[0].clientY;
    const deltaAmount = Math.round(deltaY * 0.5);
    let newAmount = state.touchStartAmount + deltaAmount;
    newAmount = Math.max(state.minAmount, Math.min(state.maxAmount, newAmount));
    newAmount = Math.round(newAmount / 5) * 5; // 5ml的增量
    
    if (state.selectedAmount !== newAmount) {
      state.selectedAmount = newAmount;
    }
    
    // 阻止滚动
    e.preventDefault();
  }
  
  function onTouchEnd(e) {
    // 滑动结束后，开始波纹衰减动画
    state.isSliding = false;
    startWaveDecay();
    
    // 阻止滚动
    e.preventDefault();
  }
  
  function onMouseDown(e) {
    // 记录起始位置
    const startY = e.clientY;
    const startAmount = state.selectedAmount;
    
    // 开始滑动，启用波纹动画
    state.isSliding = true;
    state.waveIntensity = 1; // 立即设置为最大波纹强度
    
    // 清理之前的定时器
    if (state.slideEndTimer) {
      clearTimeout(state.slideEndTimer);
    }
    if (state.waveDecayTimer) {
      clearInterval(state.waveDecayTimer);
    }
    
    // 鼠标移动和抬起事件处理
    function onMouseMove(e) {
      const deltaY = startY - e.clientY;
      const deltaAmount = Math.round(deltaY * 0.5);
      let newAmount = startAmount + deltaAmount;
      newAmount = Math.max(state.minAmount, Math.min(state.maxAmount, newAmount));
      newAmount = Math.round(newAmount / 5) * 5; // 5ml的增量
      
      if (state.selectedAmount !== newAmount) {
        state.selectedAmount = newAmount;
      }
      
      // 防止选中文本
      e.preventDefault();
    }
    
    function onMouseUp() {
      // 移除事件监听
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
      
      // 滑动结束后，开始波纹衰减动画
      state.isSliding = false;
      startWaveDecay();
    }
    
    // 添加事件监听
    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('mouseup', onMouseUp);
  }
  
  function startWaveDecay() {
    // 清理之前的衰减定时器
    if (state.waveDecayTimer) {
      clearInterval(state.waveDecayTimer);
    }

    // 开始波纹衰减动画
    state.waveDecayTimer = setInterval(() => {
      if (state.waveIntensity > 0.05) { // 最终保持轻微波纹效果
        state.waveIntensity -= 0.008; // 每次减少0.008，大约125帧后趋于平静（约2秒）
        if (state.waveIntensity < 0.05) {
          state.waveIntensity = 0.05; // 保持轻微波动
          clearInterval(state.waveDecayTimer);
          state.waveDecayTimer = null;
        }
      } else {
        // 波纹完全消失，清理定时器
        clearInterval(state.waveDecayTimer);
        state.waveDecayTimer = null;
      }
    }, 16); // 每16ms更新一次，约60fps
  }
  
  function triggerAmountBounce() {
    // 不添加bounce类，移除动画效果
    // 保留函数但不执行任何操作
  }
  
  // 禁用页面滚动
  document.body.style.overflow = 'hidden';
  
  // 处理页面卸载清理
  window.addEventListener('beforeunload', () => {
    // 清理动画定时器
    if (state.waveTimer) {
      clearInterval(state.waveTimer);
    }
    // 清理滑动结束定时器
    if (state.slideEndTimer) {
      clearTimeout(state.slideEndTimer);
    }
    // 清理波纹衰减定时器
    if (state.waveDecayTimer) {
      clearInterval(state.waveDecayTimer);
    }
  });
}); 